package file.interceptor;

import file.Constant;
import file.FileInfo;
import file.config.FsConfig;
import file.util.FileUtil;
import file.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

/**
 * @author hh
 * @since 2025/3/6
 */
@Component
public class IpInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(IpInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String ip = IpUtil.getClientIp(request);
        String decodeUrl = URLDecoder.decode(requestURI, "utf-8");
        log.info("ip: {} 请求接口: {}", ip, decodeUrl);
        String managerIp = FsConfig.get(Constant.MANAGER_IP);
        if (StringUtils.hasText(managerIp)) {
            List<String> managerIpList = Arrays.asList(managerIp.split(","));
            // 当前ip为管理员ip，无需校验白名单
            if (managerIpList.contains(ip)) {
                return true;
            }
        }

        String ipWhiteListStr = FsConfig.get(Constant.IP_WHITE_LIST);
        if (StringUtils.hasText(ipWhiteListStr)) {
            List<String> ipWhiteList = Arrays.asList(ipWhiteListStr.split(","));
            if (ipWhiteList.contains(ip)) {
                return true;
            }
        }

        if (decodeUrl.startsWith("/view")) {
            String name = decodeUrl.substring(decodeUrl.lastIndexOf("/") + 1);
            FileInfo fileInfo = FileUtil.getFileInfoByFileName(name);
            if (fileInfo == null) {
                log.error("无法找到[{}]文件", name);
                return false;
            }
            String config = FsConfig.get(fileInfo.getId());
            if (StringUtils.hasText(config)) {
                List<String> ipWhiteList = Arrays.asList(config.split(","));
                if (ipWhiteList.contains(ip)) {
                    return true;
                }
            }
        }

        noAuthority(response);
        return false;
    }

    private void noAuthority(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write("No permission");
    }

}
